<template>
    <div class="page-wrap">
      <!-- <div class="page-content"> -->
        <div class="pre-page">
          <el-button type="text" @click="goBack" class="back"><el-icon><ArrowLeft /></el-icon> 返回</el-button>
        </div>
        <div class="title">个人信息</div>
        <div class="form-wrap">
          <el-form
            class="form"
            size="large"
            :model="sendData"
            ref="InfoFormRef"
            label-width="80px"
          >
          <el-row>
            <el-col :span="12">
              <el-form-item label="角色" prop="roleName">
                <el-input
                  v-model.number="sendData.roleName"
                  autocomplete="off"
                  disabled
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="账号" prop="userName">
                <el-input
                  v-model.number="sendData.userName"
                  autocomplete="off"
                  disabled
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="姓名" prop="realName">
                <el-input
                  v-model.number="sendData.realName"
                  autocomplete="off"
                  disabled
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工号" prop="postCode">
                <el-input
                  v-model.number="sendData.postCode"
                  autocomplete="off"
                  disabled
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="部门" prop="department">
                <el-input
                  v-model.number="sendData.department"
                  autocomplete="off"
                  disabled
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="头像" prop="profilePhoto">
                <el-upload
                  class="avatar-uploader"
                  :action="uploadUrl"
                  :show-file-list="false"
                  :on-preview="handlePictureCardPreview"
                  :on-remove="handleRemove"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload"
                  :headers="uploadHeader"
                  accept=".jpg, .png, .jpeg"
                >
                <img v-if="imageUrl" alt="" :src="imageUrl" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
                <el-dialog v-model="dialogVisible">
                  <img w-full :src="imageUrl" alt="Preview Image" />
                </el-dialog>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="身份证号" prop="idCard">
                <el-input
                  v-model.number="sendData.idCard"
                  autocomplete="off"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="手机号" prop="phone">
                <el-input
                  v-model.number="sendData.phone"
                  autocomplete="off"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="入职日期" prop="entryDate">
                <el-input
                  v-model.number="sendData.entryDate"
                  autocomplete="off"
                  disabled
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="QQ" prop="qq">
                <el-input
                  v-model.number="sendData.qq"
                  autocomplete="off"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="婚否" prop="isMarried">
                <el-radio-group v-model="sendData.isMarried">
                  <el-radio v-for="item in dict.isMarried" :key="item.dictId" :label=item.dictId>{{ item.dictName }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="性别" prop="gender">
                <el-radio-group v-model="sendData.gender">
                  <el-radio v-for="item in dict.gender" :key="item.dictId" :label=item.dictId>{{ item.dictName }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="Email" prop="email">
                <el-input
                  v-model="sendData.email"
                  autocomplete="off"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="政治面貌">
                <el-select v-model="sendData.politics">
                  <el-option
                    v-for="item in dict.politics"
                    :key="item.dictId"
                    :label="item.dictName"
                    :value="item.dictId"/>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="地址" prop="address">
                <el-input
                  type="textarea"
                  v-model.number="sendData.address"
                  autocomplete="off"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item>
            <el-button type="primary" class="full-btn" @click="savePersonalInfo">确定</el-button>
          </el-form-item>
          <el-form-item>
            <el-button class="full-btn" @click="closePage">取消</el-button>
          </el-form-item>
          </el-form>
        </div>
      <!-- </div> -->
    </div>
  </template>
  
  <script setup lang="ts">
  import type { UploadProps } from 'element-plus'
  import { Plus, ArrowLeft } from '@element-plus/icons-vue'
  import urls from '@/api/staff'
  import { getInfo, updatePersonalInfo } from '@/api/staff'
  import { download, getByDictType } from '@/api/public'
  import { useStaffStore } from '@/stores/staff'

// 定义props
const props = defineProps({
  getAvatar: {
      type: Function,
      default: null
    }
  })

  let dict = reactive({
    isMarried: [{
      dictId: '',
      dictName: ''
    }],
    gender: [{
      dictId: '',
      dictName: ''
    }],
    politics: [{
      dictId: '',
      dictName: ''
    }]
  });

  let sendData = reactive({
    roleName: '',
    userName: '',
    realName: '',
    idCard: '',
    department: '',
    profilePhoto: '',
    isMarried: '',
    phone: '',
    qq: '',
    entryDate: '',
    postCode: '',
    gender: '',
    email: '',
    address: '',
    fileName: '',
    filePath: '',
    politics: ''
  })

  const dictTypes = ref('isMarried,gender,politics')
  const fileId = ref()
  
  const goBack = () => {
    closePage()
  }

  getStaffInfo(dictTypes.value)

  // 定义所要传给父组件的值
  const personalInfo = ref<boolean>()
  // 使用defineEmits注册一个自定义事件
  const emit = defineEmits(['update:updateShowValue', 'get-avatar'])

  // 获取用户详情信息
  async function getStaffInfo(dictTypes: string) {
    // 获取码表值
    await getByDictType({dictTypes: dictTypes}).then((res: any) => {
      if(res?.flag === true){
        // 需使用Object.assign给对象赋值，不然渲染有问题
        Object.assign(dict, res.data);
      }else{
        ElNotification.error(res.message)
      }
    }).catch((err: any) => {
      ElNotification.error(err)
    })

    // 获取用户信息
    await getInfo().then((res: any) => {
      if(res?.flag === true){
        const userInfo = res.data.userInfo
        Object.assign(sendData, userInfo);
        if(res.data.fileInfo !== null){
          fileId.value = res.data.fileInfo.id
        }
      }
    }).catch((err: any) => {
      ElNotification.error(err)
    })
    
    // 回显图片
    if(fileId.value !== '' && fileId.value !== null && fileId.value !== undefined){
      await download({id: fileId.value}).then((res: any) => {
      const blob = new Blob([res.data], {type: 'image/jpeg'});
      const blobUrl = URL.createObjectURL(blob);
      imageUrl.value = blobUrl
    }).catch((err: any) => {
        ElNotification.error(err)
    })
  }
    
    // 传值给父组件
    personalInfo.value = true
    emit('update:updateShowValue', personalInfo.value)
  }
  
  // 保存用户个人信息
  const savePersonalInfo = () => {
    updatePersonalInfo(sendData).then((res: any) => {
      if(res?.flag === true){
        ElNotification.success("更新成功")
        closePage()
      }
    }).catch((err: any) => {
      ElNotification.error(err)
    })
  }

  // 取消-关闭页面
  const closePage = () => {
    personalInfo.value = false
    emit('update:updateShowValue', personalInfo.value)
  }

  const imageUrl = ref('')
  const uploadUrl = urls.URL_upload_photo
  const staffStore = useStaffStore()
  const uploadHeader = {
    token: staffStore.token
  }

  // 上传成功的钩子函数
  const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
  ) => {
    if(response?.flag === true){
      imageUrl.value = URL.createObjectURL(uploadFile.raw!)
      const fileInfo = reactive({
        fileName: '',
        filePath: '',
        fileId: ''
      })
      fileInfo.fileId = response.data.id
      fileInfo.fileName = response.data.fileOriginName
      fileInfo.filePath = response.data.filePath
      updatePersonalInfo(fileInfo).then((res: any) => {
        if(res?.flag === false){
          ElNotification.error(res?.data.message)
        }else{
          ElNotification.success('头像上传成功')
          // 需更新fileId，不然头像不会刷新
          const staffStore = useStaffStore()
          staffStore.staff.fileId = fileInfo.fileId
          // 调用父组件方法
          emit('get-avatar')
        }
      }).catch((err: any) => {
        ElNotification.error(err)
      })
    }else{
      ElNotification.error(response?.message)
    }  
  }

  // 上传之前的钩子函数，限制文件格式和大小
  const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.size / 1024 / 1024 > 2) {
      ElNotification.error('大小不能超过2MB!')
      return false
    }
    return true
  }

  const dialogImageUrl = ref('')
  const dialogVisible = ref(false)
  // 文件列表移除文件时的钩子
  const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  }

  // 预览
  const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url!
    dialogVisible.value = true
  }
  </script>

  <style lang="scss" scoped>
  @use 'sass:map';
  .page-wrap {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: center;
    // align-items: center;
    flex-direction: column;
    z-index: 8;
    backdrop-filter: blur(15px);
    // background: rgba($color: #000000, $alpha: 0.2);
  }
  // 输入框边框
  :deep(.el-input.is-disabled) {
    border-radius: 5px;
    box-shadow: 0 0 0 1px var(--el-color-primary-light-3) inset;
    outline: none;
  }
  :deep(.el-form-item__label){
    font-weight: bold; /* 设置字体加重 */
  }
  .title {
    color: var(--color-text-2);
    font-size: 32px;
    margin-top: 20px;
    margin-left: 80px;
    display: flex;
    align-items: center;
    
  }

  .form{
    margin-right: 20px;
  }

  .pre-page{
    margin-left: 20px;
  }

  .form-wrap {
    margin-top: 20px;
    margin-left: 80px;
    margin-right: 80px;
    margin-bottom: 20px;
    width: calc(100% - 100px);
    max-height: 90%;
    overflow: auto;
  }
  
  .full-btn {
    width: 100%;
  }

  .avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  :deep(.avatar-uploader .el-upload) {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }

  :deep(.avatar-uploader .el-upload:hover) {
    border-color: var(--el-color-primary);
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 150px;
    height: 150px;
    text-align: center;
  }

  .form-wrap::-webkit-scrollbar {
    width: 10px;
    /*滚动条宽度*/
    height: 5px
    /*滚动条高度*/
  }
  /*定义滚动条轨道 内阴影+圆角*/
  .form-wrap::-webkit-scrollbar-track {
    /*滚动条的背景区域的内阴影*/
    box-shadow: 0px 1px 3px rgba(0, 0, 0, 0) inset;

    /*滚动条的背景区域的圆角*/
    opacity: 0;
    /*滚动条的背景颜色*/
    background-color: rgba(0, 1, 0, 0);
  }

  /*定义滑块 内阴影+圆角*/
  .form-wrap::-webkit-scrollbar-thumb {
    /*滚动条的内阴影*/
    box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.3) inset;

    /*滚动条的圆角*/
    border-radius: 10px;

    /*滚动条的背景颜色*/
    background-color: #737871;
  }
  </style>
  